package com.itheima.tlias84.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.utils.JwtUtil;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录拦截器，由spring提供
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    EmpMapper empMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始执行http请求拦截");
        //放行登录接口
//        String uri = request.getRequestURI();
//        if(uri.contains("login")){
//            return true;
//        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否有token  -> 是否绕过登录
        if (Objects.isNull(token)){
            writeErrorResponse(response,"请先登录");
            return false;
        }
        //使用jwt验证 token
        //验证token合法性
        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if(Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))){
                writeErrorResponse(response,"token不合法或已过期");
                return false;
            }
        } catch (Exception e) {
            writeErrorResponse(response,"token不合法或已过期");
            return false;
        }

        log.info("过滤完成");
        return true;
    }
    private static void writeErrorResponse(HttpServletResponse servletResponse,String msg) throws IOException {
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        //设置响应状态码
        servletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
        PrintWriter writer = servletResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        //使用fastjson 把对象转成json字符串
        writer.write(JSONObject.toJSONString(fail));
    }
}
